import Vue from "vue"
import { getCartList, updateCartList, delCartList } from "../../request/api"
let vm = new Vue();
const state = {
    cartList: [],
}
const mutations = {
    changeCartList(state, res) {
        state.cartList = res;
    },
    minusCart(state, index) {
        // if (state.cartList[index].num <= 1) {
        //     state.cartList[index].num = 1;
        //     console.log(state.cartList[index].num);
        //     // return;
        // } else {
        // }
        state.cartList[index].num--;

    },
    addCart(state, index) {
        state.cartList[index].num++;
    }
}
const actions = {
    changeCartActions(context, uid) {
        let params = {
            uid: uid
        };
        getCartList(params).then(res => {
            if (res.code === 200) {
                context.commit("changeCartList", res.list);
            }
        })
    },
    updateCartActions(context, arr) {
        let params = {
            id: arr[0],
            type: arr[1]
        };
        updateCartList(params).then(res => {
            if (res.code === 200) {
                if (params.type == 1) {
                    vm.$toast.success("数量 -1");
                    context.commit("minusCart", arr[2]);
                } else {
                    vm.$toast.success("数量 +1");
                    context.commit("addCart", arr[2]);
                }
            }
        })
    },
    delCartActions(context, id) {
        let params = {
            id: id
        };
        delCartList(params).then(res => {
            if (res.code === 200) {
                vm.$toast.success("删除成功!");
            }
        })
    }
}
const getters = {
    cart() {
        return state.cartList;
    }
}
export default {
    state,
    mutations,
    actions,
    getters,
    namespaced: true
}